package com.ykl.base.service;

import com.ykl.base.comp.EntityComp;
import com.ykl.base.jpa.BasicEntityOptions;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Optional;

public abstract class AbstractJpaCompService<T> implements EntityService<T> {

    EntityComp<T> comp;

    public AbstractJpaCompService(EntityComp<T> comp) {
        this.comp = comp;
    }

    public T save(T entity) {
        return comp.save(entity);
    }

    public List<T> save(Iterable<T> entities) {
        return comp.save(entities);
    }

    public void deleteById(String id) {
        comp.deleteById(id);
    }

    public void delete(T entity) {
        comp.delete(entity);
    }

    public void delete(Iterable<T> entities) {
        comp.delete(entities);
    }

    public void deleteByIds(Iterable<String> ids) {
        comp.deleteByIds(ids);
    }

    public Optional<T> findById(String id) {
        return comp.findById(id);
    }

    protected Pageable buildPageable(int pgIdxB0, int pgSize, List<Sort.Order> sorts) {
        Pageable pg;
        if(CollectionUtils.isEmpty(sorts)){
            pg = PageRequest.of(pgIdxB0, pgSize);
        }else {
            pg = PageRequest.of(pgIdxB0, pgSize, Sort.by(sorts));
        }
        return pg;
    }

    @Override
    public List<T> listAll() {
        return comp.listAll();
    }

    @Override
    public List<T> listAll(Sort sort) {
        return comp.listAll(sort);
    }
}